<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="110px">
      <el-form-item label="部门名称：" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="部门编码：" prop="code">
        <el-input v-model="form.code" />
      </el-form-item>

      <el-form-item label="部门负责人：" width="650px" prop="manager">
        <el-select v-model="form.manager" style="width:675px" placeholder="请选择部门负责人">
          <el-option v-for="obj in list" :key="obj.id" :label="obj.username" :value="obj.username" />

        </el-select>
      </el-form-item>

      <el-form-item label="部门介绍：" prop="introduce">
        <el-input v-model="form.introduce" type="textarea" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('form')">{{ popId.isEdit?'修改':'立即创建' }}</el-button>
        <el-button @click="removeFn">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { NewDepartmentAPI, EmployeeInformationAPI, ModifyDepartmentAPI, QueryDepartmentAPI } from '@/api/departmentsAPI'

export default {
  name: 'Depatment',
  props: {
    popId: { // 父组件传过来的 编辑时请求需要的ID与是否编辑状态
      type: Object,
      required: true
    },
    departmentList: { // 父组件传过来的 所有部门数据
      type: Array,
      required: true
    }

  },
  data() {
    // 部门编码验证==========================>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    const validatePass = (to, value, beraer) => {
      let arr = this.departmentList.map(itme => itme.code)
      if (this.popId.isEdit) {
        arr = this.departmentList.filter(itme => itme.id !== this.popId.id).map(itme => itme.code)
      }
      arr.includes(value) ? beraer(Error(`这个编码${value}重复了`)) : beraer()
    }
    // 部门名称验证==========================>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    const nameValidatePas = (to, value, beraer) => {
      // 声明 Myname,Myment 全局
      let Myname = null
      let Myment = null
      let app = null
      let arr = this.departmentList.map(itme => itme.name)
      // app 找出输入框输入的部门pid
      app = this.departmentList.find(itme => {
        if (itme.name === value) {
          return itme
        } else {
          return false
        }
      })
      console.log(app)

      if (app) {
        // 寻找相同名称的父部门或子部门
        Myment = this.departmentList.find(itme => itme.id === app.pid)
        // 找出当前正在编辑的名称 通过ID寻找==> "this.popId.id" 与当前ID相同的  用find找到后返回自身
        Myname = this.departmentList.find(itme => itme.id === this.popId.id)
        // 判断pid是否相同，相同说明为同级部门
      }
      // 编辑状态时 ==> "this.popId.isEdit" 编辑当前的ID ==>" this.popId.id"
      if (this.popId.isEdit) {
        // Myname 就是当前编辑的name 用filter寻找同级部门，pid相等说明它们是同级别，在用ID寻找和当前ID不同的排除当前的name
        arr = this.departmentList.filter(itme => itme.id !== Myname.id).map(itme => itme.name)
      }

      if (app && app.pid !== Myname.pid) {
        arr.includes(value) ? beraer(Error(`"${Myment.name}"下的子部门名称"${value}"已存在`)) : beraer()
        return
      }
      arr.includes(value) ? beraer(Error(`同级部门名称"${value}"已存在`)) : beraer()
    }
    return {
      form: {
        name: '', // 部门名称
        manager: '', // 部门负责人
        code: '', // 部门编码
        introduce: '', // 部门介绍
        pid: '' // 父级部门ID

      },
      list: [], // 请求回来的数据
      // 验证
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 2, max: 13, message: '长度在 2 到 13 个字符', trigger: 'blur' },
          {
            validator: nameValidatePas, trigger: 'blur'
          }
        ],
        manager: [
          { required: true, message: '请选择部门负责人', trigger: 'change' }

        ],
        code: [
          { required: true, message: '请填写编码', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请填写介绍', trigger: 'blur' },
          { min: 1, max: 300, message: '长度在 2 到 13 个字符', trigger: 'blur' }
        ]
      }
    }
  },

  created() {
    this.EmployeeInformation()
  },

  methods: {

    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          !this.popId.isEdit ? this.NewDepartment() : this.ModifyDepartment()
          this.$emit('phpfalse')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    removeFn() {
      this.form = {
        name: '', // 部门名称
        manager: '', // 部门负责人
        code: '', // 部门编码
        introduce: '', // 部门介绍
        pid: '' // 父级部门ID

      }
      this.$emit('remove')
    },

    // 新增部门功能
    async  NewDepartment() {
      const res = await NewDepartmentAPI({ ...this.form, pid: this.popId.id })
      this.$message.success('添加成功')
      console.log(res)
    },

    // 编辑部门
    async  ModifyDepartment() {
      await ModifyDepartmentAPI(this.form)
      this.$message.success('修改成功')
    },

    // 获取员工简单列表
    async   EmployeeInformation() {
      const res = await EmployeeInformationAPI()
      this.list = res.data
      // 查询部门详情
      if (this.popId.isEdit) {
        const res = await QueryDepartmentAPI(this.popId.id)
        this.form = res.data
      } else {
        this.form = {
          name: '', // 部门名称
          manager: '', // 部门负责人
          code: '', // 部门编码
          introduce: '', // 部门介绍
          pid: '' // 父级部门ID

        }
      }
    }

  }
}
</script>

<style >
.el-form{
   padding: 0 40px 0 20px;
}

.el-dialog__header{
    background-color: rgb(4, 108, 243);

}
 .el-dialog__title{
color: aliceblue;
    }
</style>
